/**
 * xdemo.org
 */
package org.xdemo.site.system.bean.sqlinxml;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xdemo.site.system.exception.KeyRepetitionException;

/**
 * @作者 Goofy
 * @邮件 252878950@qq.com
 * @日期 2014-1-22
 * @描述 初始化SQL语句的集合，在程序中引用，实现SQL语句与程序的解耦
 */
public class XmlReader {

	public String[] xmlPath;

	private final Map<String, String> SQLMap = new HashMap<String, String>();

	@SuppressWarnings("unchecked")
	public void init() throws DocumentException, KeyRepetitionException {
		
		SAXReader reader = new SAXReader();
		File xmlFile = null;
		Document doc = null;
		Element module = null;
		List<Element> clazz = null;
		List<Element> method = null;
		List<Element> sql = null;
		String key = "";
		String classpath=this.getClass().getResource("/").getPath().toString();
		
		for (String s : xmlPath) {
			xmlFile = new File(classpath+s);
			doc = reader.read(xmlFile);
			module = doc.getRootElement();
			clazz = module.elements();
			// package-class-method-index
			for (Element e1 : clazz) {
				method = e1.elements();
				for (Element e2 : method) {
					sql = e2.elements();
					for (Element e3 : sql) {
						key = module.attributeValue("name") + "-"
								+ e1.attributeValue("name") + "-"
								+ e2.attributeValue("name") + "-"
								+ e3.attributeValue("index").toLowerCase();
						if (SQLMap.containsKey(key)) {
							throw new KeyRepetitionException(key);
						}
						SQLMap.put(key.toLowerCase(), e3.getTextTrim());
					}
				}
			}
		}
		
		Iterator ite = SQLMap.entrySet().iterator();
		while (ite.hasNext()) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>)ite.next();
			System.out.println("索引："+entry.getKey() + "\t\t 值：" + entry.getValue());
		}
	}

	/**
	 * 获取SQL语句
	 * 
	 * @param key key的格式为:包名-类名-方法名-第几条sql语句(因为一个方法中可能有多个语句)
	 * @return String | null
	 */
	public String getSQL(String key) {
		key = key.toLowerCase();
		return SQLMap.containsKey(key) == true ? SQLMap.get(key) : null;
	}

	/**
	 * @param xmlPath
	 *            the xmlPath to set
	 */
	public void setXmlPath(String... xmlPath) {
		this.xmlPath = xmlPath;
	}

}
